<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class ApprovalController extends \MLM\Model\Generic\Controller
{
        
    public function indexAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return new ViewModel();

    }
    


    public function withdrawlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        $view = new ViewModel();

        
        return $view;

    }


    public function topuplistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view = new ViewModel();        

        return $view;

    }


    public function approvewithdrawAction(){

        $identity = $this->hasSession();
        $this->layout('layout/admin');
        $view = new ViewModel();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $flag = $post['flag'];


            $dataW = $storage->approveWithdraw($transId, $flag);
            while($dataW->next()){
                    $res = $dataW->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approvewithdraw?msg='.$flag.' Penarikan Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }

            //return $this->redirect()->toUrl('approvewithdraw?msg='.$flag.' Penarikan Sukses');
            //die();
            
        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $storage->getTransDetail($transId);
        while($dataTrans->next()){
            
                $res = $dataTrans->current();
                $data['account_num1'] = $res['account_num1'];
                $data['amount1'] = number_format($res['amount1']);
                $data['bank'] = "[".$res['bank_acc_no']."] ".$res['bank_name']." ".$res['bank_acc_name'];
                
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('msg', $msg);

        return $view;
        
    }

    public function approvetopupAction(){

        $identity = $this->hasSession();
        $this->layout('layout/admin');
        $view = new ViewModel();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $flag = $post['flag'];


            $dataT = $storage->approveTopup($transId, $flag);
            while($dataT->next()){
                    $res = $dataT->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approvetopup?msg='.$flag.' TopUp Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }

            //return $this->redirect()->toUrl('approvewithdraw?msg='.$flag.' Penarikan Sukses');
            //die();

        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $storage->getTransDetail($transId);
        while($dataTrans->next()){
                $res = $dataTrans->current();
                
                $data = array_merge($data, $res);
                

        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('msg', $msg);

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript('
          jQuery(function($) {
            $("textarea[class*=autosize]").autosize({append: "\n"});
        })
        ');

        return $view;

    }

    public function topupAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return new ViewModel();


    }


    public function buysnAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return new ViewModel();


    }

    public function buyproductAction()
    {
        $identity = $this->hasSession();
        $this->layout('layout/admin');
        $view = new ViewModel();

        $memberId = $identity->member_id;

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        if ($request->isPost()) {
            $conn->beginTransaction();
            $formData = $request->getPost();

            $sn   = $formData['sn'];
            $snList   = $formData['snList'];
            $flag   = $formData['flag'];
            
            $err = 0;
            $errorMsg = "";

            /*
             * Check List
             */
            if ($snList == "" && $flag == 1){
                $errorMsg .= "* SN harus dipilih.<br>";
                //return;
                $err = 1;
            }


            $msg = "";
            if ($err == 0){

                    if ($flag == 1){ //Aktifkan yang dipilih
                        $msg = "Diaktifkan";
                    }else if ($flag == 2){ //Aktifkan semua
                        $msg = "Diaktifkan Semua";
                    }else if ($flag == 3){  //Pasifkan semua
                        $msg = "Dipasifkan Semua";
                    }

                    $storage = new \MLM\Model\Sn\Storage($db);
                    $res = $storage->aktivasiSN($snList, $flag, $sn);

                    if(!$res){
                        $conn->rollback();
                        $view->setVariable('msg', 'SN Gagal '.$msg);
                        return $view;
                    }

                    $conn->commit();
                    $view->setVariable('msg', 'SN Berhasil '.$msg);
                    return $view;

            }else{
              
                $view->setVariable('errmsg', $errorMsg);
                return $view;
            }



        }else{
            
            return $view;
        }

       
    }


    public function confirmlistAction(){
        $identity = $this->hasSession();
        if ($identity->member_type_id == 4)
            $this->layout('layout/admin');
        else
            $this->layout('layout/member');
            
        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return $view;
   }

    public function payconfirmAction(){
        $identity = $this->hasSession();
        if ($identity->member_type_id == 4)
            $this->layout('layout/admin');
        else
            $this->layout('layout/member');
            
        $view = new ViewModel();

        $request = $this->getRequest();
        $memberId = $identity->member_id;

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Transaction\Storage($db);
        
        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();
            $confirmId = $post["confirmId"];

            $data = array(
                'payment_status'  => 1
            );
            $where = array('payment_confirm_id' => $confirmId);
            $res = $storage->updateConfirmPaymentStatus($data, $where);

            $conn->commit();

            return $this->redirect()->toUrl('payconfirm?msg=Verifikasi Pembayaran Sukses');


            die();
        }
        
        $getParams = $this->getRequest()->getQuery();
        $confirmId = $getParams["confirmId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataConfirm = $storage->getConfirmPaymentDetail($confirmId);
        while($dataConfirm->next()){
                $res = $dataConfirm->current();
                $data['trans_code'] = $res['trans_code'];
                $data['amount1'] = number_format($res['amount1']);
                $data['pay_date'] = $res['pay_date2'];

                if ($res['pay_method'] == 1) $data['pay_method'] = "Transfer ATM";
                else if ($res['pay_method'] == 2) $data['pay_method'] = "Internet Banking";
                else if ($res['pay_method'] == 3) $data['pay_method'] = "Mobile Banking";
                else $data['pay_method'] = "Setoran/Transfer Tunai";

                $data['from_account'] = "[".$res['from_acc_no']."] ".$res['from_bank']." ".$res['from_acc_name'];
                //$data['to_account'] = "[".$res['to_acc_no']."] ".$res['to_bank']." ".$res['to_acc_name'];

                if ($res['to_account_id'] == 1)
                    $data['to_account'] = "BCA Norek: 28-307-11-841, A/N CUCU SYAMSUL MILLAH, Cabang Ujungberung Bandung";
                else if ($res['to_account_id'] == 2)
                    $data['to_account'] = "BRI Norek: 0750-01-025013-53-0, A/N CUCU SYAMSUL MILLAH, Cabang Cibiru Bandung";
                else if ($res['to_account_id'] == 3)
                    $data['to_account'] = "BNI Norek: 002-453-1955, A/N CUCU SYAMSUL MILLAH, Cabang Majalengka";
                else if ($res['to_account_id'] == 4)
                    $data['to_account'] = "MANDIRI Norek: 131-00-0726422-1, A/N CUCU SYAMSUL MILLAH, Cabang Ujungberung Bandung";

                
                $data['transfer_amount'] = number_format($res['transfer_amount']);
                $data['notes'] = $res['notes'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        $view->setVariable('data', $data);
        $view->setVariable('confirmId', $confirmId);
        $view->setVariable('msg', $msg);

        return $view;
   }


   public function buysnlistAction(){
        $identity = $this->hasSession();
        
        if($identity->member_type_id == 4) $this->layout('layout/admin');
        else $this->layout('layout/member');

        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
   }


   public function approvalbuysnAction(){

        $identity = $this->hasSession();

        if($identity->member_type_id == 4) $this->layout('layout/admin');
        else $this->layout('layout/member');
        
        $view = new ViewModel();

        $request = $this->getRequest();
        $memberId = $identity->member_id;

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $flag = $post['flag'];


            $dataA = $storage->approveBuySN($transId, $flag);
            while($dataA->next()){
                    $res = $dataA->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approvalbuysn?msg='.$flag.' Pembelian SN Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }

            //return $this->redirect()->toUrl('approvalbuysn?msg='.$flag.' Pembelian SN Sukses');
            //die();

        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $storage->getTransDetail($transId);
        while($dataTrans->next()){

                $res = $dataTrans->current();
                $data['trans_code'] = $res['trans_code'];
                $data['trans_dtm'] = $res['trans_dtm'];
                $data['account_num1'] = $res['account_num1'];
                $data['jumlah'] = number_format($res['xn2']);
                $data['amount1'] = number_format($res['amount1']);

                if ($res['xs3'] == 1) $data['carabayar'] = "Cash";
                else if ($res['xs3'] == 2) $data['carabayar'] = "Tukar Point";
                else $data['carabayar'] = "Transfer";
                
        }


        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('msg', $msg);

        return $view;

    }


    public function buyproductlistAction(){
        $identity = $this->hasSession();
        if ($identity->member_type_id == 4)
            $this->layout('layout/admin');
        else
            $this->layout('layout/member');
            
        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
   }


   public function approvalbuyproductAction(){

        $identity = $this->hasSession();
        if ($identity->member_type_id == 4)
            $this->layout('layout/admin');
        else
            $this->layout('layout/member');
            
        $view = new ViewModel();

        $request = $this->getRequest();

        $memberId = $identity->member_id;

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $flag = $post['flag'];


            $dataA = $storage->approveBuyProduct($transId, $flag);
            while($dataA->next()){
                    $res = $dataA->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approvalbuyproduct?msg='.$flag.' Pembelian Produk Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }

            //return $this->redirect()->toUrl('approvalbuysn?msg='.$flag.' Pembelian SN Sukses');
            //die();

        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $storage->getTransHeader($transId);
        while($dataTrans->next()){

                $res = $dataTrans->current();
                $data['trans_code'] = $res['trans_code'];
                $data['trans_dtm'] = $res['trans_dtm'];
                $data['account_num1'] = $res['account_num1'];
                $data['jumlah'] = number_format($res['xn2']);
                $data['amount1'] = number_format($res['amount1']);
                $data['produk'] = $res['xs2'];

                $arrSup = explode("-", $res['xs1']);
                $data['suplier'] = $arrSup[1];

                if ($res['xs3'] == 1) $data['carabayar'] = "Cash";
                else if ($res['xs3'] == 2) $data['carabayar'] = "Tukar Point";
                else $data['carabayar'] = "Transfer";

        }


        $dataDetailTrans = $storage->getTransDetailProduct($transId);


        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('dataDetailTrans', $dataDetailTrans);
        $view->setVariable('msg', $msg);

        return $view;

    }


    public function agentlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view = new ViewModel();

        return $view;

    }


    public function approveagentAction(){

        $identity = $this->hasSession();
        $this->layout('layout/admin');
        $view = new ViewModel();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $transStorage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $memberId   = $post['memberId'];
            $flag = $post['flag'];
            $agentSN = "";
            $agentPIN = "";

            // Jika Approve
            if ($flag == "APPROVE"){
                $memberStorage = new \MLM\Model\Member\Storage($db);
                $member = new \MLM\Model\Member($memberStorage);
                $snStorage = new \MLM\Model\Sn\Storage($db);

                // GET SN PT
                $num = "";
                $sn = "";
                $stts = 2;
                $start = 0;
                $limit = 1;
                $search = "true";
                $searchField = "agent_id = 100";

                $snPT = $snStorage->getSN($num, $sn, $stts, $start, $limit, $search, $searchField);

                $agentSN = $snPT[1][0]["SN"];
                $agentPIN = $snPT[1][0]["PIN"];


                //Jika SN PT tidak tersedia
                if ($agentSN == ""){

                    // GENERATE New SN

                    $getPrefix = $snStorage->getSNConfig('SN_PREFIX');
                    while($getPrefix->next()){
                            $res = $getPrefix->current();
                            $prefix = $res['str_value'];
                    }


                    $getLen = $snStorage->getSNConfig('SN_NUMBER_LENGTH');
                    while($getLen->next()){
                            $res = $getLen->current();
                            $len = $res['int_value'];
                    }


                    $resSN = $snStorage->genSN($prefix, $len);
                    $resArr = explode(",", $resSN);
                    $agentSN = $resArr[0];
                    $agentPIN = $resArr[1];
                }           
            }
            
            $dataA = $transStorage->approveAgent($transId, $memberId, $agentSN, $agentPIN, $flag);
            while($dataA->next()){
                    $res = $dataA->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approveagent?msg='.$flag.' Pendaftaran Agen Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }
            

        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $transStorage->getTransDetail($transId);
        while($dataTrans->next()){

                $res = $dataTrans->current();
                $data['account_num1'] = $res['account_num1'];
                $data['account_name'] = $res['account_name'];
                $data['memberId'] = $res['member_id'];
                $data['address'] = $res['xs5'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('msg', $msg);

        return $view;

    }


    public function claimrewardlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view = new ViewModel();

        return $view;

    }


    public function approverewardAction(){

        $identity = $this->hasSession();
        $this->layout('layout/admin');
        $view = new ViewModel();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $transStorage = new \MLM\Model\Transaction\Storage($db);

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId   = $post['transId'];
            $memberId   = $post['memberId'];
            $bonurRewardId = $post['bonurRewardId'];
            $flag = $post['flag'];
                         

            $dataA = $transStorage->approveReward($transId, $bonurRewardId, $flag);
            while($dataA->next()){
                    $res = $dataA->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                return $this->redirect()->toUrl('approvereward?msg='.$flag.' Klaim Reward Sukses');

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }       

        }

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $data = array();

        $dataTrans = $transStorage->getTransDetail($transId);
        while($dataTrans->next()){

                $res = $dataTrans->current();
                $data['account_num1'] = $res['account_num1'];
                $data['account_name'] = $res['account_name'];
                $data['memberId'] = $res['member_id'];
                $data['rewardName'] = $res['xs1'];
                $data['bonurRewardId'] = $res['xn1'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view->setVariable('data', $data);
        $view->setVariable('transId', $transId);
        $view->setVariable('msg', $msg);

        return $view;

    }


   //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){

        $identity = $this->hasSession();

        /*
        if ($memberId == 100) $memberId2 = $memberId;
        else{

            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }
         *
         */

        $isAgent = $identity->member_reff_id;
        $memberCode = $identity->member_code;


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);

        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }


   private function hasSession() {
        $auth = new AuthenticationService();

        //$identity = $auth->getIdentity();

        if (!$auth->hasIdentity()) {
            //return $this->redirect()->toRoute('admin', array('controller' => 'Admin', 'action' => 'login'));
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }

}

